package com.isaac.config;

import com.isaac.pojo.Configuration;
import com.isaac.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> select = rootElement.selectNodes("select");
        List<Element> insert = rootElement.selectNodes("insert");
        List<Element> update = rootElement.selectNodes("update");
        List<Element> delete = rootElement.selectNodes("delete");
        doCreateMappedStatement(namespace,select,insert,update,delete);
    }

    /**
     * 封装 mappedstatement
     * @param namespace
     * @param params
     */
    private void doCreateMappedStatement(String namespace, List<Element>...params){
        for (List<Element> param : params) {
            for (Element element : param) {
                String id = element.attributeValue("id");
                String parameterType = element.attributeValue("parameterType");
                String resultType = element.attributeValue("resultType");
                // statementId
                String key = namespace + "." + id;
                // sql
                String textTrim = element.getTextTrim();

                // 封装mappedStatment
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setParameterType(parameterType);
                mappedStatement.setResultType(resultType);
                mappedStatement.setSql(textTrim);

                // 填充configuration
                configuration.getMappedStatementMap().put(key,mappedStatement);
            }
        }
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        return Class.forName(parameterType);
    }
}
